/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sirtet.netplay;

import sirtet.GameBoard;
import sirtet.Player;

/**
 * A network player serving at the client side, wrapping a local player whose
 * actions will be relayed to the server and wait for bounce-back.  If server
 * bounces back the action, it then performs the requested action.
 * @author guangwei.zhu
 */
public class SynchronizedPlayer extends NetworkPlayer {

    private Player localPlayer;
    private final Object lock = new Object();
    protected boolean synced = false;

    public SynchronizedPlayer(Player localPlayer, Communicator comm) {
        // Create a network player who shares the same player ID
        super(localPlayer, comm);

        this.localPlayer = localPlayer;

        // Connect it to the remote peer
        PlayerPipe.connect(localPlayer, comm);
    }

    @Override
    public boolean ready() {
        synchronized (lock) {
            return synced;
        }
    }

    protected void setSync(boolean value) {
        synchronized (lock) {
            this.synced = value;
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        this.localPlayer.setEnabled(enabled);
    }

    @Override
    public void bindBoard(GameBoard board) {
        super.bindBoard(board);
        localPlayer.bindBoard(board);
    }

    @Override
    public void unbindBoard(GameBoard board) {
        super.unbindBoard(board);
        localPlayer.unbindBoard(board);
    }

    /**
     * Calling this function will cause this instance to be unuseable.
     * This invocation is necessary to cause this object to be garbage-collected.
     */
    protected void dispose() {
        PlayerPipe.disconnect(this.localPlayer, this.communicator);
    }
}
